import requests
from multiprocessing import Process, Pool
from threading import Thread
import time


def request(url):
    url = "https://www.baidu.com/s"
    request_body = "ct=2&logFrom=recdetail&logid=0&ssid=30ad82e4&sid=1425_33045_32946_33060_31254_32705_33099_33101_32961&curRid=9606770753583294089&qid=0&tid=142&cst=2&logExtra=%7B%22rid%22%3A%22%22%2C%22pos%22%3A%22%22%2C%22extra%22%3A%22%22%2C%22isBaiJiaHao%22%3A%221%22%2C%22login%22%3A%221%22%7D&r=l1605342737885"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"
    }
    response = requests.get(f"{url}?{request_body}", headers=headers)
    time.sleep(1)
    print(f"response status:{response.status_code}")
    return response.status_code


if __name__ == "__main__":
#多线程
    start_time = time.time()
    mul_line_list = []
    for i in range(5):
        t = Thread(target=request, args=("https://www.126.com/s",))
        t.start()
        mul_line_list.append(t)
    [t.join() for t in mul_line_list]
    end_time = time.time()
    print(f"多线程运行结束，总共用时：{end_time - start_time}s")

#多进程
    start_time = time.time()
    mul_process_list = []
    for i in range(5):
        p = Process(target=request, args=("https://www.126.com/s",))
        p.start()
        mul_process_list.append(p)
    [p.join() for p in mul_process_list]
    end_time = time.time()
    print(f"多进程运行结束，总共用时：{end_time - start_time}s")

#进程池（4核）
    start_time = time.time()
    pool = Pool(4)
    process_pool = []
    for i in range(5):
        future = pool.apply_async(request, args=("https://www.126.com/s",))
        process_pool.append(future)
    pool.close()
    pool.join()
    end_time = time.time()
    print(f"进程池运行结束，总共用时：{end_time - start_time}s")
    print("进程池中的期物如下：")
    for f in process_pool:
        print(f.get())